<?php

namespace app\home\controller;

use app\common\controller\Home;

// 微信公众号SDK
use addons\wechat\library\Config;
use addons\wechat\model\WechatAutoreply;
use addons\wechat\model\WechatCaptcha;
use addons\wechat\model\WechatContext;
use addons\wechat\model\WechatResponse;
use addons\wechat\model\WechatConfig;

use EasyWeChat\Factory;
use addons\wechat\library\Wechat as WechatService;
use addons\wechat\library\Config as ConfigService;
use think\Log;

/**
 * 课程控制器
 */
class Subject extends Home
{
    // 不需要登录的方法
    protected $noNeedLogin = ['search','subject', 'likes'];

    // 构造函数
    public function __construct()
    {
        // 继承分类
        parent::__construct();

        // 创建模型
        $this->SubjectModel = model('Subject.Subject');

        $this->ListsModel = model('Subject.Lists');

        $this->OrderModel = model('Subject.Order');

        $this->RecordModel = model('Business.Record');

        $this->BusinessModel = model('Business.Business');

        // 配置微信公众号
        $this->app = Factory::officialAccount(Config::load());
    }

    // 搜索
    public function search()
    {
        // 接收关键词
        $keywords = $this->request->param('keywords', '', 'trim');

        // 封装条件
        $where = [];

        // 判断关键字是否为空
        if(!empty($keywords))
        {
            $where['title|content'] = ['like', "%$keywords%"];
        }

        $sublist = $this->SubjectModel->where($where)->select();

        $this->view->assign([
            'sublist'=>$sublist,
            'keywords'=>$keywords,
        ]);

        return $this->view->fetch();
    }

    // 课程界面
    public function subject($subid = 0)
    {
        // 根据课程id去查询课程的信息
        $subject = $this->SubjectModel->find($subid);

        // 默认没点赞
        $likes = false;

        // 判断课程是否存在
        if(!$subject)
        {
            $this->error('课程不存在');
            exit;
        }

        // 获取cookie
        $LoginAuth = cookie('LoginAuth') ? cookie('LoginAuth') : [];

        $busid = isset($LoginAuth['id']) ? $LoginAuth['id'] : 0;

        $busmobi = isset($LoginAuth['mobile']) ? $LoginAuth['mobile'] : '';

        // 根据id 和 手机号找出这个人
        $where = [
            'id' => $busid,
            'mobile' => $busmobi,
        ];

        // 单条查询
        $business = $this->BusinessModel->where($where)->find();

        // 说明有登录
        if($business)
        {
            $str = trim($subject['likes']);
            $arr = explode(',', $str);
            $arr = array_filter($arr);

            // 如果在说明点赞过了
            $likes = in_array($busid, $arr) ? true : false;
        }

        // 查找课程的章节
        $lists = $this->ListsModel->where(['subid' => $subid])->order('createtime ASC')->select();

        // 查找评论
        $comment = $this->OrderModel
            ->with(['subject', 'business'])
            ->where(['subid' => $subid])
            ->order('createtime ASC')
            ->select();

        // var_dump(collection($comment)->toArray());
        // exit;

        $this->view->assign([
            'subject' => $subject,
            'lists' => $lists,
            'likes' => $likes,
            'comment' => $comment,
        ]);

        return $this->view->fetch();
    }

    // 点赞功能
    public function likes()
    {
        // Thinkphp 判断 是否为 ajax的请求
        if($this->request->isAjax())
        {
            // 获取cookie
            $LoginAuth = cookie('LoginAuth') ? cookie('LoginAuth') : [];

            $busid = isset($LoginAuth['id']) ? $LoginAuth['id'] : 0;

            $busmobi = isset($LoginAuth['mobile']) ? $LoginAuth['mobile'] : '';

            // 根据id 和 手机号找出这个人
            $where = [
                'id' => $busid,
                'mobile' => $busmobi
            ];

            // 单条查询
            $business = $this->BusinessModel->where($where)->find();

            if(!$business)
            {
                cookie('LoginAuth',null);
                // code = 0
                $this->error('请先登录');
            }

            // 接收课程id
            $subid = $this->request->param('subid', 0);

            // 根据id查询，查询课程是否存在
            $subject = $this->SubjectModel->find($subid);

            if(!$subject)
            {
                $this->error('课程不存在');
                exit;
            }
            // 字符串变成数组
            $likes = explode(',', $subject['likes']);
            // 数组要去除空元素
            $likes = array_filter($likes);

            $msg = "点赞成功";

            // 如果在数组中就取消点赞，如果不在就增加点赞
            if(in_array($busid, $likes))
            {
                // 取消
                foreach($likes as $key=>$item)
                {
                    if($item == $busid)
                    {
                        unset($likes[$key]);
                        break;
                    }
                }

                $msg = "取消点赞";
            }else
            {
                // 增加
                $likes[] = $busid;

                $msg = '点赞';
            }

            // 组装数据准备更新
            $data = [
                'id' => $subid,
                'likes' => implode(',', $likes) // 从数组在变回字符串
            ];

            $result = $this->SubjectModel->isUpdate(true)->save($data);

            if($result === false)
            {
                $this->error("{$msg}失败");
                exit;
            }else
            {
                $this->success("{$msg}成功");
                exit;
            }
        }
    }

    // 课程播放
    public function play()
    {
        if($this->request->isAjax())
        {
            // 接收课程id
            $subid = $this->request->param('subid', 0);
            $listid = $this->request->param('listid', 0);

            // 获取到用户id
            $busid = $this->LoginAuth['id'];

            //根据课程id 和 用户id 去找 有没有 购买订单 有订单就说明购买过可以看
            //如果没有订单 就说明没买过 就不能看

            $where = [
                'subid' => $subid,
                'busid' => $busid
            ];

            $order = $this->OrderModel->where($where)->find();

            if(!$order)
            {
                $this->error('请先购买课程', null, 'buy');
                exit;
            }
            // 如果有章节id 就查询指定的章节，如果没有章节id 就默认查询第一个
            $where = [
                'subid' => $subid
            ];

            if($listid)
            {
                $where['id'] = $listid;
            }

            $list = $this->ListsModel->where($where)->order('createtime asc')->find();

            if($list)
            {
                // 成功查询到章节，并返回
                $this->success('返回章节数据成功', null, $list);
                exit;
            }else
            {
                $this->error('暂无章节数据');
                exit;
            }
        }
    }

    // 购买课程
    public function buy()
    {
        // 判断是否为ajax请求
        if($this->request->isAjax())
        {
            // 获取当前购买的课程id
            $subid = $this->request->param('subid', 0);
            $busid = $this->LoginAuth['id'];

            // 根据id去查询课程是否存在
            $subject = $this->SubjectModel->find($subid);

            if(!$subject)
            {
                $this->error('课程不存在');
                exit;
            }

            // 判断是否已经购买过
            $where = [
                'busid'=>$busid,
                'subid'=>$subid
            ];

            $order = $this->OrderModel->where($where)->find();

            if($order)
            {
                $this->error('该课程已经购买过 ，无需重复购买');
                exit;
            }

            // 课程价格
            $price = isset($subject['price']) ? trim($subject['price']) : 0;

            // 个人余额
            $money = isset($this->LoginAuth['money']) ? trim($this->LoginAuth['money']) : 0;

            // 个人余额 - 课程价格
            $UpdateMoney = bcsub($money, $price);

            if($UpdateMoney < 0)
            {
                $this->error('余额不足，请先充值');
                exit;
            }

            // 开启操作表的事务
            $this->OrderModel->startTrans();
            $this->BusinessModel->startTrans();
            $this->RecordModel->startTrans();

            // 生成订单号
            $code = build_code("SU");

            // 订单表  插入
            $OrderData = [
                'subid' => $subid,
                'busid' => $busid,
                'total' => $price,
                'code' => $code,
            ];

            // 插入订单表
            $OrderStatus = $this->OrderModel->validate('common/Subject/Order')->save($OrderData);

            // 订单插入失败
            if($OrderStatus === FALSE)
            {
                $this->error($this->OrderModel->getError());
                exit;
            }

            // 更新用户表
            $BusData = [
                'id' => $busid,
                'money' => $UpdateMoney
            ];

            // 判断成交状态，如果是为未成交，就改成以成交
            if(!$this->LoginAuth['deal'])
            {
                // 变成已成交
                $BusData['deal'] = 1;
            }

            // 更新
            $BusStatus = $this->BusinessModel->isUpdate(true)->save($BusData);

            // 更新用户失败
            if($BusStatus === FALSE)
            {
                // 订单要回滚
                $this->OrderModel->rollback();
                $this->error($this->BusinessModel->getError());
                exit;
            }

            // 插入消费记录表
            $subtitle = $subject['title'];
            $RecordData = [
                'total' => "-{$price}",
                'content' => "购买了 【{$subtitle}】课程，花费了 ￥{$price}元",
                'busid' => $busid
            ];

            // 插入消费记录表
            $RecordStatus = $this->RecordModel->validate('common/Business/Record')->save($RecordData);

            // 消费记录插入失败
            if($RecordStatus === FALSE)
            {
                $this->BusinessModel->rollback();
                $this->OrderModel->rollback();
                $this->error($this->RecordModel->getError());
                exit;
            }

            if($OrderStatus === FALSE || $BusStatus === FALSE || $RecordStatus === FALSE)
            {
                $this->RecordModel->rollback();
                $this->BusinessModel->rollback();
                $this->OrderModel->rollback();
                $this->error('购买失败');
                exit;
            }else
            {
                //3个步骤都成功了 3个模拟的步骤都要提交事务 真正执行到数据库中
                $this->OrderModel->commit();
                $this->BusinessModel->commit();
                $this->RecordModel->commit();

                // 发送模板消息
                $createtime = date("Y-m-d H:i", time());

                $url = url('/home/subject/subject', ['subid' => $subid], true, true);

                $this->app->template_message->send([
                    // 模板消息接收方
                    'touser' => 'oJhcF501LHvgwFRga5dI-0vO2syg',
                    // 模板id
                    'template_id' => 'FARflK3qs_32GdCEQMqTCSbwPY6foPwNMtAIWn3IEJI',
                    // 跳转地址
                    'url' => $url,
                    // 模板数据
                    'data' => [
                        'title' => '标题：您购买了一套课程',
                        'user' => "用户名：".$this->LoginAuth['nickname'],
                        'content' => "描述：您共消费 $price 元",
                        'createtime' => "消费时间：$createtime"
                    ]
                ]);
                $this->success('购买成功');
                exit;
            }
        }
    }

    // 购买完成
    public function complete($subid = 0)
    {
        $subject = $this->SubjectModel->find($subid);

        // 如果课程不存在，就返回课程列表页面
        if(!$subject)
        {
            $this->error('课程不存在',url('/home/subject/search'));
            exit;
        }

        $this->view->assign('subid', $subid);

        return $this->view->fetch();
    }
}
